import { createStore } from 'vuex';

const setLocalCartList = (state) => {
  const { cartList } = state;
  const cartListString = JSON.stringify(cartList);
  localStorage.cartList = cartListString;
};

const getLocalCartList = () => {
  console.log(localStorage.cartList);
  return JSON.parse(localStorage.cartList || '{}');
};

export default createStore({
  state: {
    cartList: getLocalCartList(),
    //  {
    // shopId: {
    // shopName: '沃尔玛',
    // productList: {
    //   productId: {
    //     _id: 1,
    //     name: 'xxx',
    //     imgUrl: 'xxx',
    //     sales: '11',
    //     count: 0,
    //   },
    // },
    // },
    // },
  },
  getters: {},
  mutations: {
    // 商品信息
    changeCartItemInfo(state, payload) {
      // console.log(payload); //{shopId: '1', productId: '1', productInfo: Proxy}
      const { shopId, productId, productInfo } = payload;
      let shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {},
      };
      // console.log(shopInfo);
      let product = shopInfo.productList[productId];
      if (!product) {
        productInfo.count = 0;
        product = productInfo;
      }
      product.count = product.count + payload.num;
      payload.num > 0 && (product.check = true);
      product.count < 0 && (product.count = 0);
      shopInfo.productList[productId] = product;
      state.cartList[shopId] = shopInfo;
      setLocalCartList(state);
    },
    // 修改商品名称
    changeShopName(state, payload) {
      const { shopId, shopName } = payload;
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {},
      };
      shopInfo.shopName = shopName;
      state.cartList[shopId] = shopInfo;
      setLocalCartList(state);
    },
    // 是否选中
    changeCartItemChecked(state, payload) {
      const { shopId, productId } = payload;
      const product = state.cartList[shopId].productList[productId];
      product.check = !product.check;
      setLocalCartList(state);
    },
    // 清空购物车
    cleanCartProduct(state, payload) {
      const { shopId } = payload;
      state.cartList[shopId].productList = {};
      setLocalCartList(state);
    },
    // 是否全选
    setCartAllChecked(state, payload) {
      const { shopId, selectALL } = payload;
      // console.log(selectALL);
      const products = state.cartList[shopId].productList;
      if (products) {
        for (const key in products) {
          const product = products[key];
          // console.log(product.check);
          product.check = !selectALL;
        }
      }
      setLocalCartList(state);
    },
    cleanCartData(state, shopId) {
      delete state.cartList[shopId];
    },
  },
  actions: {},
  modules: {},
});
